﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerArchitecture.Core;
using ComputerArchitecture.Core.Logging;
using ComputerArchitecture.Numbers;
using ComputerArchitecture.Units.Interfaces;

namespace ComputerArchitecture.Units.Shifted
{
    public class ShiftedNegateUnit : LoggingObject, INegateUnit
    {
        #region Constructors

        public ShiftedNegateUnit(ILoggingService loggingService) 
            : base(loggingService)
        {
        }

        #endregion

        public ISignedBitNumber Negate(ISignedBitNumber value, out NegateSpecialCase specialCase, out bool hasError)
        {
            ArgumentValidator.NullValidate(value);
            if (value.IsZero)
            {
                hasError = false;
                specialCase = NegateSpecialCase.Zero;
                return ShiftedBitNumber.GetZero(value.Size);
            }
            ISignedBitNumber min = ShiftedBitNumber.GetMin(value.Size);
            if (value.Equals(min))
            {
                hasError = true;
                specialCase = NegateSpecialCase.MaxNegativeValue;
                return min;
            }
            specialCase = NegateSpecialCase.None;
            hasError = false;
            ISignedBitNumber result = (ISignedBitNumber) value.Clone();
            if (result[0].IsSet)
            {
                result[0].Reset();
            }
            else
            {
                result[0].Set();
            }
            return result;
        }
    }
}
